import React, {useEffect, useState} from 'react';
import { useHistory } from "react-router-dom";
import http from "../../../model/http";
import {PullToRefresh, DatePicker, List, Flex, Modal, Button, SwipeAction, Toast} from "antd-mobile";
import './history.less';
import '../../../libs/font/iconfont.css'
import {dateFormat, sendMsg} from '../../../model/code';
import Header from "../../../components/header/Header";
import img1 from '../../../libs/img/user/billingHistrory1.png'
import img2 from '../../../libs/img/user/billingHistrory2.png'
import img3 from '../../../libs/img/user/billingHistrory3.png'
import deleteImg from '../../../libs/img/user/deleteImg.png'


import qrCode from '../../../libs/img/user/qrCode.png'

let page = 1;
const h = document.documentElement.clientHeight - 100;
function Project() {
  const history = useHistory();
  const nowTimeStamp = new Date(); 
  const [date,setDate] = useState(nowTimeStamp);
  const [date2,setDate2] = useState(nowTimeStamp)

  const [list,setList] = useState([]);
  const [load,setLoad] = useState(false);
   
  const getList = (status)=>{
    (async ()=>{
      setLoad(true);
    
      const _list = await http.post('/order/orderlist',{ 
        page:page,
        items:10,
        begintime: dateFormat(date,'yyyy-MM-dd'),
        endtime: dateFormat(date2,'yyyy-MM-dd'),
      })
      setTimeout(()=>{setLoad(false)},800)
      if(status == 'clearArr'){
        setList([..._list.data]);
      }else{
        if(!_list.data.length) return;
        // page++;
        setList([...list,..._list.data]);
      }
      page=page+1
      
    })()
  }

  useEffect(()=>{
    list.length || getList();

    return ()=>{
      page=1
    }
    // eslint-disable-next-line
  },[])

   

  // 查询
  const submitSearch = () => { 
    page=1 
    setList([])
    getList('clearArr')
  }

  // 移除 
  const editRemove = (item) => {
    if(item.is_show_cancel !== 1){
      Toast.fail('该订单已支付，无法作废！')
      return 
    } 
    Modal.alert('提示', '确定作废这条记录吗', [
      { text: '取消' },
      {
        text: '确定', onPress: async () => {
          const delResult = await http.post('/order/order_cancel',{ 
            wxwork_bill_id: item.wxwork_bill_id,
            service_id: item.service_id
          })
          if(delResult.code == 0){
            Toast.success(delResult.msg) 
            setTimeout(() => {
              submitSearch() 
            }, 500);  
          }else{
            Toast.fail(delResult.msg)
          }
        }
      }
    ])
  }


  const openQrcode = (code) =>{  
      Modal.alert('QrCode', 
          <div> 
            <img src={code} style={{width:"200px",height:"200px"}}></img>
          </div>
          , [{ text: '确定' }]
      )
  }
   

  return (
    <div className='v-billing-history-list'>
      <List className='g-mb10 g-p5-10 g-bg-f g-bdrs12 appointmentRecord-list-search-box'>
         
        <Flex>
          <Flex.Item> 
            <DatePicker mode="date" value={date}  onChange={d=>{
                setDate(d)
                 
                let dateNum = new Date(d).getTime()
                let date2Num = new Date(date2).getTime()
                if(Number(dateNum) > Number(date2Num)){
                  setDate2(d) 
                }  
                
              }}>  
              <List.Item arrow="horizontal"></List.Item>
            </DatePicker>    
          </Flex.Item>
          <Flex.Item>
            <DatePicker mode="date" value={date2} minDate={date}  onChange={d=>{setDate2(d)}}>  
              <List.Item arrow="horizontal"></List.Item>
            </DatePicker>
          </Flex.Item>
          <Flex.Item><Button type="primary" size="small" className="appointmentRecord-list-search" onClick={() => submitSearch()}>查询</Button></Flex.Item>
        </Flex>
        
      </List>
      <PullToRefresh direction='up' onRefresh={getList} refreshing={load} style={{height:h, overflow:'auto',paddingTop:'70px',fontSize:'14px'}}>
        
        {/* i.displayname */}
        
        {list.length > 0 ?
          list.map((i,idx)=>(
            <SwipeAction
              disabled={i.is_show_cancel != 1 ? true : false}
              style={{ marginBottom:'10px' }}
              autoClose
              right={[ 
                {
                  text: <span style={{fontSize:'25px'}} className="iconfont icon-shanchu1"></span>,
                  onPress: () => editRemove(i),
                  style: { backgroundColor: '#dd524d', color: 'white', fontSize:'25px',paddingLeft: "20px",paddingRight:'20px' },
                },
              ]}
              onOpen={() => console.log('global open')}
              onClose={() => console.log('global close')}
            >
              <div className='v-p18 g-bdrs12 g-bg-f g-mb10 card-box'> 
                <p className='g-f14 g-mb10 card-box-title' style={{marginBottom:'0'}}>提交人：{i.creator}&emsp;开单人：{i.deducter} </p>

                <p className='v-lh20 g-c8 v-f13 card-box-p' style={{margin:'3px 0 7px 0'}}>顾客姓名：{i.customerName}&emsp;顾客卡号：{i.card_no}</p>

                <p className='g-f14 g-mb10 card-box-title' dangerouslySetInnerHTML={{ __html: i.itemnames}}></p> 
                <p className='v-lh20 g-c8 v-f13 card-box-p'>成交金额：{(i.billMoney).toFixed('2')}&emsp;应付金额：{(i.totalMoney).toFixed('2')}</p>
                {/* <p className='v-lh20 g-c8 v-f13 card-box-p'>成交状态：{i.charge_state_name}</p> */}
                <p className='v-lh20 g-c8 v-f13 card-box-p'>开单时间：{i.create_time}</p>
                <p className='v-lh20 g-c8 v-f13 card-box-p'>成交时间：{i.processedTime}</p>  
                {/* {i.charge_state == 0 ? <img src={img1} />:(i.charge_state == 2?<img src={img2} />:(i.charge_state == 1?"未收完":''))} */}

                {i.charge_state == '0' && (<img className='img' src={img1} />)} 
                {i.charge_state == '1' && (<img className='img' src={img3} />)}  
                {i.charge_state == '2' && (<img className='img' src={img2} />)}   
                {i.charge_state == '-1' && (<img className='img' src={deleteImg} />)}    
                 
                 {/* i.orderQRCode */}
                {i.charge_state == '0' && (<img onClick={ ()=>{ openQrcode(i.orderQRCode) } } src={qrCode} className="qrCode"></img>)} 
                            
              </div>  
            </SwipeAction>
          ))
        :<div style={{color:'#bbb',textAlign:'center',fontSize:'14px'}}>暂无数据</div>}
        
 
 
      </PullToRefresh>
      <Header />
    </div>
  )
}
// crdId --- serviceId
// tb_customer_id --- customerCrmId
// hosId srid
export default Project;

// 待支付 0
// 未收完 1
// 已支付 2
// 已取消 -1